package com.freesun.shop.aspect;

import cn.hutool.json.JSONUtil;
import com.freesun.shop.anno.Log;
import com.freesun.shop.entity.SysLog;
import com.freesun.shop.entity.SysUser;
import com.freesun.shop.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private SysLogService sysLogService;
    //只要有Log注解,就进入切面
    //@Around("execution(* com.freesun.shop.controller .* .*(..))")
    @Around("@annotation(com.freesun.shop.anno.Log)")
    public Object recordLog(ProceedingJoinPoint point) throws Throwable {
        SysLog sysLog=new SysLog();
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysLog.setUsername(user.getUsername());
        //获取当前的方法签名
        MethodSignature methodSignature =  (MethodSignature) point.getSignature();
        //获取的可能是代理的方法
        Method proxyMethod= methodSignature.getMethod();
        String name = methodSignature.getMethod().getName();

        sysLog.setMethod(name);
        //操作 ,实际执行的方法对象
        Method realMethod = null;

            realMethod = point.getTarget().getClass().getMethod(name,proxyMethod.getParameterTypes() );

        //获取到log注解
        Log log = realMethod.getAnnotation(Log.class);
        sysLog.setOperation(log.name());
        //需要一个ip地址工具类
        sysLog.setIp("127.0.0.1");
        sysLog.setParams(JSONUtil.toJsonStr(point.getArgs()==null?"{参数为Null}":point.getArgs()));
        long start = System.currentTimeMillis();
        Object result=null;

             result = point.proceed(point.getArgs());


        long end = System.currentTimeMillis();
        sysLog.setTime(end-start);
        sysLog.setCreateDate(LocalDateTime.now());
        sysLogService.save(sysLog);
        return result;
    }
}
